<template>
<div class="UserControl">
    <!-- 主要内容（form表单） -->

    <el-dialog title="用户导入" :visible.sync="importUserdialogVisible" width="30%" :before-close="importUserHandleClose">
        <el-form :model="form">
            <el-form-item label="文件导入">
                <UploadFiles></UploadFiles>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="importUserdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="importUserdialogVisible = false">确 定</el-button>
        </div>
    </el-dialog>

    <!-- <ImportXlsx title="主体导入" type="subject" :ImportXlsxShow="ImportXlsxShow"></ImportXlsx> -->

    <el-row>
        <el-col :span="24">
            <el-card>
                <el-col :span="4" style="padding-bottom: 15px">
                    <el-card>
                        <div slot="header" class="clearfix">
                            <span>组织机构</span>
                        </div>

                        <el-input placeholder="输入关键字进行过滤" maxlength="10" show-word-limit v-model="filterText">
                        </el-input>

                        <el-tree @node-click="selectUsers" class="filter-tree" :data="OrganizationTree" :props="defaultProps" :default-expand-all="false" :filter-node-method="filterNode" ref="tree">
                        </el-tree>
                    </el-card>
                </el-col>
                <el-col :span="20" style="padding-bottom: 15px">
                    <el-card>
                        <el-form :inline="true" class="demo-form-inline">
                            <el-form-item label="用户等级">
                                <el-select v-model="userLevel" clearable placeholder="请选择用户等级搜索">
                                    <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="身份证号">
                                <el-input v-model="registerCard" placeholder="请输入身份证号搜索" maxlength="18" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="手机号码">
                                <el-input v-model="filterphone" placeholder="请输入手机号码搜索" maxlength="11" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="用户名">
                                <el-input v-model="keywords" placeholder="请输入用户名或姓名" maxlength="20" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="searchPhone">查询</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                    <el-card>
                        <div slot="header" class="clearfix">
                            <span>用户信息</span>
                        </div>
                        <el-table :data="filterList && filterList.length ? filterList : List" fixed style="width: 100%">
                            <el-table-column fixed prop="userId" label="ID" width="50">
                            </el-table-column>
                            <el-table-column fixed prop="username" label="登录帐号" width="150">
                            </el-table-column>
                            <el-table-column prop="realName" label="姓名" width="130">
                            </el-table-column>
                            <el-table-column prop="mobile" label="手机" width="150">
                            </el-table-column>
                            <el-table-column prop="organName" label="部门" width="180">
                            </el-table-column>
                            <el-table-column prop="organName" label="状态">
                                <template slot-scope="scope">
                                    {{ userStatusCn(scope.row.status) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" width="350">
                                <template slot="header">
                                    <el-button type="primary" size="medium" @click="adduser(0)">新建</el-button>
                                    <el-button type="danger" size="medium" @click="importUser">导入</el-button>
                                </template>

                                <template slot-scope="scope">
                                    <el-button @click="handleClick(scope.row)" type="text" size="small">查看
                                    </el-button>
                                    <el-button @click="deleteUser(scope.row.userId)" type="text" size="small">删除
                                    </el-button>
                                    <el-button @click="adduser(scope.row.userId)" type="text" size="small">编辑
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination background @size-change="handleSizeChange" @current-change="currentChange" :current-page="params.pageNumber" :page-sizes="[5, 10, 20, 30, 40]" :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="params.total">
                        </el-pagination>
                    </el-card>
                </el-col>
            </el-card>
        </el-col>
    </el-row>

    <el-dialog title="查看用户" :visible.sync="lookdialogFormVisible" width="40%">
        <el-card class="detail">
            <ul>
                <li><span>登录账号</span> :{{ form.username }}</li>
                <li><span>姓名</span> :{{ form.realName }}</li>
                <li><span>手机号码</span> :{{ form.mobile }}</li>
                <li><span>创建时间</span> :{{ form.createTime }}</li>
            </ul>
        </el-card>
    </el-dialog>

    <!-- 新增用户弹框 -->
    <el-dialog :title="isAddOrEdit ? '新建用户' : '修改用户'" :visible.sync="dialogFormVisible" width="40%">
        <el-form :model="form" ref="form" :rules="rules" label-width="90px">

            <el-row>
                <el-col span="12">
                    <el-form-item label="账号" prop="account">
                        <el-input v-model="form.account" maxlength="11" show-word-limit :disabled="inputDisabled"></el-input>
                    </el-form-item>
                </el-col>
                <el-col span="12">
                    <el-form-item label="姓名" prop="userName">
                        <el-input v-model="form.userName" maxlength="15" show-word-limit :disabled="inputDisabled"></el-input>
                    </el-form-item>
                </el-col>
                <el-col span="12">
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="form.password" maxlength="18" show-word-limit type="password"></el-input>
                    </el-form-item>
                </el-col>
                <el-col span="12">
                    <el-form-item label="重复密码" prop="password2">
                        <el-input v-model="form.password2" maxlength="18" show-word-limit type="password"></el-input>
                    </el-form-item>
                </el-col>
                <el-col span="24">
                    <el-form-item label="所属权限" prop="">
                        <el-radio v-model="radio" label="1">组织机构</el-radio>
                        <el-radio v-model="radio" label="2">镇街</el-radio>
                    </el-form-item>
                </el-col>
                <el-col span="24">
                    <el-form-item v-if="radio == 1" label="组织机构" prop="organization">
                        <el-cascader v-model="form.organization" collapse-tags :options="OrganizationTree" :props="optionProps" @change="handleChange">
                        </el-cascader>
                    </el-form-item>

                </el-col>
                <el-col span="12">
                    <el-form-item v-if="radio == 2" label="选择镇街">
                        <el-select v-model="form.subjectTownId" @change="changeOptions">
                            <el-option v-for="(item, index) in options" :key="item.value" :label="item.label" :value="item.value" @click.native="getIndex(index)"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col span="12">
                    <el-form-item v-if="radio == 2" label="选择村居">
                        <el-select v-model="form.subjectVillageId">
                            <el-option v-for="item in options[townIndex].children" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col span="12">
                    <el-form-item label="联系方式" prop="phone">
                        <el-input v-model="form.phone" maxlength="11" show-word-limit></el-input>
                    </el-form-item>
                </el-col>
                <el-col span="12">
                    <el-form-item label="身份证号">
                        <el-input v-model="form.registerCard" minlength="15" maxlength="18" show-word-limit></el-input>
                    </el-form-item>
                </el-col>

                <el-col span="12">
                    <el-form-item label="身份等级" prop="level">
                        <el-select v-model="form.level" placeholder="请选择">
                            <el-option v-for="item in optionsLevel" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col span="12">
                    <el-form-item label="角色">
                        <el-select v-model="form.roleIds" prop="roleId" multiple placeholder="请选择">
                            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item>
                <el-button @click="onSubmit('form')" type="primary">保存</el-button>
            </el-form-item>

        </el-form>
    </el-dialog>
</div>
</template>

<script>
import {
    checkPhone
} from "@/library/regexp.js";
import {
    convertKey,
    formatDate
} from "@/library";
import {
    mapGetters
} from "vuex";
import axios from "@/api/request.js";

export default {
    name: "UserControl",
    data() {
        return {
            radio: "1",
            userLevel: "",
            registerCard: "",
            filterphone: "",
            keywords: "",
            selectOptions: [{
                    value: "3",
                    label: "区级用户",
                },
                {
                    value: "4",
                    label: "镇街用户",
                },
                {
                    value: "5",
                    label: "村居用户",
                },
            ],
            inputDisabled: false,
            optionsLevel: [{
                    value: 3,
                    label: "区级管理员",
                },
                {
                    value: 4,
                    label: "镇街管理员",
                },
                {
                    value: 5,
                    label: "村居信息员",
                },
            ],
            importUserdialogVisible: false,
            townIndex: 0,
            defaultProps: {
                children: "children",
                label: "label",
                value: "value",
                id: "id",
            },
            roleList: [],
            optionProps: {
                checkStrictly: true,
            },
            filterText: "",
            dialogFormVisible: false,
            form: {
                account: "",
                userName: "",
                password: "",
                password2: "",
                organization: [],
                phone: "",
                userId: "",
                level: "",
                roleId: "",
                roleIds: [],
                idCard: "",
                subjectTownId: "", //所属镇 (区域编码) 必填
                subjectVillageId: "", //所属村 (区域编码)
                administrativeCode: "", //行政编码
            },
            search: "",
            checked: false,

            //正则验证
            rules: {
                account: [{
                    required: true,
                    message: "账号不能为空",
                    trigger: "blur",
                }, ],
                userName: [{
                    required: true,
                    message: "姓名不能为空",
                    trigger: "blur",
                }, ],
                password: [{
                    required: true,
                    message: "密码不能为空",
                    trigger: "blur",
                }, ],
                password2: [{
                    required: true,
                    message: "确认密码不能为空",
                    trigger: "blur",
                }, ],
                organization: [{
                    required: true,
                    message: "请至少选择一项",
                    trigger: "change",
                }, ],
                phone: [{
                    required: true,
                    validator: checkPhone("请填写正确格式的手机号码"),
                    trigger: "blur",
                }, ],
                subjectTownId: [{
                    required: true,
                    message: "请至少选择一项",
                    trigger: "change",
                }, ],
                roleId: [{
                    required: true,
                    message: "请至少选择一项",
                    trigger: "change",
                }, ],
                level: [{
                    required: true,
                    message: "请至少选择一项",
                    trigger: "change",
                }, ],
            },
            props: {
                children: "children",
                label: "label",
            },
            params: {
                pageNumber: 1,
                pageSize: 10,
            },
            paging: {},

            OrganizationTree: [],
            List: [],
            OrganizationList: [],
            row: {},
            disabled: false,
            lookdialogFormVisible: false,
            detail: {},
            documentClick: false,
            filterList: [],
            isAddOrEdit: true,
        };
    },
    created() {
        this.UserControl(1, 10, null, 1);
        this.Organization();
    },

    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        },
    },
    mounted() {
        // document.addEventListener('click', () => {
        //     if (this.documentClick) {
        //         this.UserControl()
        //         this.filterList = []
        //         this.documentClick = false
        //     }
        // })
    },
    computed: {
        ...mapGetters({
            options: "getTreeData/filtersVillage",
        }),
    },
    methods: {
        importUserHandleClose() {
            this.$confirm("确认关闭？")
                .then((_) => {
                    done();
                })
                .catch((_) => {});
        },
        importUser() {
            this.importUserdialogVisible = true;
        },
        searchPhone() {
            this.$fishing
                .UserControl(
                    1,
                    10,
                    null,
                    1,
                    this.filterphone,
                    this.keywords,
                    this.registerCard,
                    this.userLevel
                )
                .then((res) => {
                    this.List = res.data.list;
                    this.filterList = res.data.list;
                    this.params.pageNumber = res.data.pageNum;
                    this.params.pageSize = res.data.pageSize;
                    this.params.total = res.data.total;
                });
        },
        deleteUser(id) {
            this.$confirm("警告警告！此操作将永久删除该用户, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(() => {
                    axios
                        .post(`rbac/sysuser/delete`, {
                            params: {
                                userIds: id,
                            },
                        })
                        .then((res) => {
                            if (res && res.errorCode == "00000") {
                                this.$message({
                                    type: "success",
                                    message: "删除成功!",
                                });
                                this.UserControl(1, 10, this.form.organization, 1);
                            }
                        });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },

        changeOptions(selVal) {
            console.log(selVal);
            this.form.subjectVillageId = "";
        },
        getIndex(val) {
            this.townIndex = val;
        },
        selectUsers(itemName) {
            console.log(itemName);
            this.filterList = [];
            this.form.organization = itemName.value;
            // this.UserControl(this.params.pageNumber, this.params.pageSize, itemName.id, 1)
            this.$fishing
                .UserControl(
                    this.params.pageNumber,
                    this.params.pageSize,
                    this.form.organization,
                    1
                )
                .then((res) => {
                    if (res.data) {
                        if (res.data.list && res.data.list.length != 0) {
                            this.filterList = res.data.list;
                            this.params.pageNumber = res.data.pageNum;
                            this.params.pageSize = res.data.pageSize;
                            this.params.total = res.data.total;
                        } else {
                            this.List = [];
                            this.filterList = [];
                            this.params.pageNumber = 1;
                            this.params.pageSize = 10;
                            this.params.total = 0;
                        }
                    }
                });
            this.documentClick = true;
            return false;
        },
        // 搜索筛选左侧信息
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },

        // account: "",
        // userName: "",
        // password: "",
        // password2: "",
        // organization: [],
        // phone: "",
        // userId: "",
        // street: "",
        // level: "",
        // roleId: 3,

        adduser(id) {
            if (id > 0) {
                this.form.userId = id;
                this.isAddOrEdit = false;
                this.rules.password[0].required = false;
                this.rules.password2[0].required = false;
                this.inputDisabled = true;
            } else {
                this.form.userId = "";
                this.form.account = "";
                this.form.password = "";
                this.form.phone = "";
                this.isAddOrEdit = true;
            }
            this.$common.RolePermission(this.form).then((res) => {
                this.roleList = res.data.list;
                if (this.form.userId) {
                    this.$common.getUserDetailInfo(this.form).then((res) => {
                        this.disabled = false;
                        this.dialogFormVisible = true;
                        this.form.account = res.data.list[0].username;
                        this.form.userName = res.data.list[0].realName;
                        this.form.phone = res.data.list[0].registerTele;
                        this.form.registerCard = res.data.list[0].registerCard;
                        this.form.roleIds = res.data.list[0].roleIds;
                        this.form.level = res.data.list[0].userLevel;
                        this.form.phone = res.data.list[0].mobile;
                        this.form.organization = res.data.list[0].organId;
                        // this.form.organization.push(res.page.list[0].organCode);

                        if (res.data.list[0].userLevel == 4) {
                            //this.form.subjectTownId = res.page.list[0].administrativeHigh;
                        }
                        if (res.data.list[0].userLevel == 5) {
                            //this.form.subjectTownId = res.page.list[0].administrativeHigh;
                            //this.form.subjectVillageId = res.page.list[0].userAdministrativeCode;
                        }
                        if (res.data.list[0].userLevel == 3) {
                            this.form.subjectTownId = "";
                            this.form.subjectVillageId = "";
                        }
                    });
                } else {
                    this.disabled = false;
                    this.dialogFormVisible = true;
                }
            });
        },
        // 点击确定事件
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    console.log("form", this.form);

                    //如果角色为镇街管理员 则必须选择一个镇街
                    if (this.form.level == 4 && this.form.subjectTownId == "") {
                        this.$message("角色为镇街管理员，则必须选择一个镇街");
                        return false;
                    } else if (
                        this.form.level == 5 &&
                        (this.form.subjectTownId == "" || this.form.subjectVillageId == "")
                    ) {
                        this.$message("角色为街道管理员必须选择镇街和街道");
                        return false;
                    } else {
                        //验证两次输入密码是否正确
                        if (this.form.password != this.form.password2) {
                            this.$message("两次输入的密码不一致，请重新输入");
                            return false;
                        }

                        if (this.form.level == 4 && this.form.subjectTownId != "") {
                            this.form.level = 4;
                            this.form.administrativeCode = this.form.subjectTownId;
                        } else if (
                            this.form.level == 5 &&
                            this.form.subjectTownId != "" &&
                            this.form.subjectVillageId != ""
                        ) {
                            this.form.level = 5;
                            this.form.administrativeCode = this.subjectVillageId;
                        } else {
                            //默认南海区
                            this.form.level = 3;
                            this.form.administrativeCode = "440605";
                        }

                        console.log("待提交form", this.form);

                        this.$common.createOrUpdateUser(this.form).then((res) => {
                            if (res && res.errorCode == "00000") {
                                this.$message({
                                    message: "操作成功",
                                    type: "success",
                                    duration: 1500,
                                    onClose: () => {
                                        this.Organization();
                                        this.UserControl(1, 10, null, 1);
                                        this.dialogFormVisible = false;
                                    },
                                });
                            } else {
                                this.$message.error(res.errorMsg);
                            }
                        });
                    }
                } else {
                    return false;
                }
            });
        },

        handleClick(row) {
            this.form = row;
            this.form.createTime = formatDate(row.createTime);
            this.lookdialogFormVisible = true;
        },
        // 关闭弹框的事件
        closeDialog() {
            this.dialogFormVisible = false;
        },
        // 点击取消事件
        cancelFun() {
            this.dialogFormVisible = false;
        },

        //树形结构节点的点击事件
        handleNodeClick() {},
        statusChange(item) {
            console.log(item);
        },
        userStatusCn(index) {
            var Status = {
                0: "待审核",
                1: "审核通过",
                2: "审核不通过",
            };

            return Status[index];
        },
        onSearch() {},

        handleSizeChange(pageSize) {
            this.params.pageSize = pageSize;
            this.$fishing
                .UserControl(
                    this.params.pageNumber,
                    this.params.pageSize,
                    null,
                    1,
                    this.filterphone,
                    this.keywords,
                    this.registerCard,
                    this.userLevel
                )
                .then((res) => {
                    console.log(res);
                    this.List = res.data.list;
                    this.filterList = res.data.list;
                    this.params.pageNumber = res.data.pageNum;
                    this.params.pageSize = res.data.pageSize;
                    this.params.total = res.data.total;
                });
        },
        currentChange(pageNumber) {
            this.params.pageNumber = pageNumber;
            this.$fishing
                .UserControl(
                    this.params.pageNumber,
                    this.params.pageSize,
                    null,
                    1,
                    this.filterphone,
                    this.keywords,
                    this.registerCard,
                    this.userLevel
                )
                .then((res) => {
                    console.log(res);
                    this.List = res.data.list;
                    this.filterList = res.data.list;
                    this.params.pageNumber = res.data.pageNum;
                    this.params.pageSize = res.data.pageSize;
                    this.params.total = res.data.total;
                });
        },
        Organization(pageNumber = 1, pageSize = 10) {
            this.$common.Organization(pageNumber, pageSize).then((res) => {
                console.log(res.data.list);
                this.OrganizationTree = res.data.list.reverse();
                this.OrganizationTree = convertKey(this.OrganizationTree, {
                    organName: "label",
                    organCode: "value",
                });
            });
        },

        UserControl(pageNumber = 1, pageSize = 10, organId, status) {
            console.log(organId);
            this.filterList = [];
            this.$fishing
                .UserControl(pageNumber, pageSize, organId, status)
                .then((res) => {
                    if (res.data) {
                        if (res.data.list && res.data.list.length != 0) {
                            this.List = res.data.list;
                            this.filterList = res.data.list;
                            this.params.pageNumber = res.data.pageNum;
                            this.params.pageSize = res.data.pageSize;
                            this.params.total = res.data.total;
                        } else {
                            this.List = [];
                            this.filterList = [];
                            this.params.pageNumber = 1;
                            this.params.pageSize = 10;
                            this.params.total = 0;
                        }
                    }
                });
        },

        handleChange(value) {
            console.log(value);
        },
    },
};
</script>

<style lang="scss">
.UserControl {
    padding-bottom: 15px;

    .form {
        padding: 15px 10px;
    }

    .el-card {
        width: 98%;
        margin: 15px auto 0;

        .bottom {
            display: flex;
            justify-content: flex-end;
            margin-top: 15px;
        }
    }
}
</style>
